<template>
  <div class="jnpf-content-wrapper">
    <div class="jnpf-content-wrapper-left m-2">
      <BasicLeftTree
        title="项目实施主责单位"
        ref="leftTreeRef"
        :loading="treeLoading"
        :treeData="industryTypeList"
        :showSearch="!isFlow"
        :defaultExpandAll="false"
        @reload="reloadTree"
        @select="handleTreeSelect"
        showToolbar />
    </div>

    <div class="IlmsForm flex-1">
      <div class="IlmsForm-content flex flex-col">
        <div class="row">
          <div v-if="!isFlow" class="search-list">
            <JnpfInput
              v-model:value="keyword"
              placeholder="请输入姓名"
              style="width: 400px"
              :disabled="isFlow"
              maxLength="15"></JnpfInput>
            <a-Button :loading="searchLoading" type="primary" :disabled="isFlow" @click="searchHandle">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-Button>
          </div>
          <div class="project-label">项目经理：
            <Tag v-if="curUer.realName" color="blue">{{ curUer.realName }}</Tag>
            <span v-else>--</span>
          </div>
        </div>
        <div v-if="isFlow" class="active name-eare">{{ curUer.realName }}</div>
        <div class="flex-1 createProjectSelect">
          <div
            class="info"
            v-for="(item, index) in userList"
            :key="index"
            :class="{ active: curUer.userId === item.id }"
            @click="usersClick(item)">
            <P>{{ item.realName }}</P>
          </div>
          <Loading tip="加载中" :loading="isLoading" style="width: 120%" />
          <jnpf-empty v-if="!userList.length && !isLoading" class="h-50% w-full" />
        </div>
        <!-- <a-pagination size="small" :total="50" style="width: 100% !important; height: 50px !important" /> -->
      </div>
      <div class="IlmsForm-footer" v-if="!isFlow">
        <a-space>
          <a-button size="middle" @click="submit('0')"> 暂存 </a-button>
          <a-button type="primary" size="middle" @click="submit('1')"> 提交 </a-button>
        </a-space>
      </div>
    </div>
  </div>
</template>

<script lang="ts" name="ManagerAppointForm" setup>
  import { Tag } from 'ant-design-vue';
  import { Loading } from '@/components/Loading';
  import { BasicLeftTree, TreeActionType } from '@/components/Tree';
  import { getCompanyOrBusinessUnitList } from '@/api/permission/organize'; // 公司单位接口
  import { getCompanyUserList } from '@/api/permission/user'; // 公司单位接口
  // import { getUserList } from '@/api/permission/user';
  // import { getCodeDetail } from '../projectManage/common/api';
  import { orgManagerSave, changeManager } from '@/views/project/preSale/managerAppoint/common/api';
  import { useMessage } from '@/hooks/web/useMessage';
  import { getLatestDetailCode } from '@/views/project/contract/common/api';
  import { isEmpty } from '@/utils/is';
  import { SearchOutlined } from '@ant-design/icons-vue';

  const { createMessage } = useMessage();

  const props = defineProps({
    // 审批流相关配置
    config: {
      type: Object,
      default: () => {},
    },
    salesCode: {
      type: String,
      default: '',
    },
  });

  /***
   * 审批流
   * setPageLoad：设置流程加载状态
   * eventReceiver：流程操作事件接受
   * openRevokeFlow：打开流程图
   * closePopup：关闭弹窗
   */
  const emits = defineEmits(['submited', 'setPageLoad', 'eventReceiver', 'openRevokeFlow', 'closePopup']);
  // 是否为审批流
  const isFlow = computed(() => {
    return props.config?.flowId;
  });

  const emitter = inject<any>('emitter');
  const fid = inject<Ref<string>>('fid', ref(''));
  const orgManagerId = inject<Ref<string>>('orgManagerId', ref(''));
  const isNewVersion = inject<Ref<boolean>>('isNewVersion', ref(false));

  interface State {
    industryTypeList: any[];
    userList: any[];
    treeLoading: boolean;
    curUer: any; // 当前选中的人
    keyword: string;
    searchLoading: boolean;
    isLoading: boolean;
    total: number;
    current: number;
    pageSize: number;
  }

  const state = reactive<State>({
    industryTypeList: [],
    userList: [],
    treeLoading: false,
    curUer: {},
    keyword: '',
    searchLoading: false,
    isLoading: false,
    total: 10,
    current: 1,
    pageSize: 50,
  });
  const {
    industryTypeList,
    treeLoading,
    userList,
    curUer,
    keyword,
    searchLoading,
    isLoading,
    total,
    pageSize,
  } = toRefs(state);
  const leftTreeRef = ref<Nullable<TreeActionType>>(null);
  const selectTreeId = ref('');

  const searchHandle = async () => {
    if (!keyword.value) return getDeptUserList();
    state.searchLoading = true;
    try {
      const res = await getCompanyUserList({ organizeId: selectTreeId.value, keyword: keyword.value });
      state.userList = res.data;
      state.searchLoading = false;
    } catch (error) {
      state.userList = [];
      state.searchLoading = false;
    }
  };

  // 初始左边机构树的数据【是审批页面，就过滤只显示对应人员的机构】
  async function reloadTree() {
    state.treeLoading = true;
    const res = await getCompanyOrBusinessUnitList({ queryType: 'companiesAndCenters' });
    // 左边机构数据, 展开节点处理
    state.industryTypeList = res.data.list.map(item => ({
        ...item,
        // 子项为空，是否是叶子节点设置为true
        isLeaf: Array.isArray(item.children) && item.children.length === 0
      })
    );
    if (isFlow.value && !isNewVersion.value) {
      // state.industryTypeList = res.data.list.map(item => {
      //   let obj = item;
      //   obj['disabled'] = true;
      //   return obj;
      // });
      console.log("1.2-左边机构树数据", res.data);
      
      state.industryTypeList = state.industryTypeList.filter(item => 
        item.id === curUer.value.orgId
      );
    }
    nextTick(() => {
      state.treeLoading = false;
      getDetail('');
    });
  }

  function handleTreeSelect(id: string) {
    if (isFlow.value) return;
    selectTreeId.value = id;
    getDeptUserList();
  }

  const usersClick = (item: any) => {
    if (isFlow.value) return;
    state.curUer = { ...item, userId: item.id };
  };

  const getDeptUserList = async () => {
    state.isLoading = true;
    try {
      const res = await getCompanyUserList({ organizeId: selectTreeId.value });
      state.userList = res.data;
      state.isLoading = false;
    } catch (error) {
      state.isLoading = false;
    }
  };

  const submit = async (type: string) => {
    let where = {};
    if(isNewVersion.value){
      let info = (await changeManager(fid.value))?.data;
      where = {
        changeFromId: info.changeFromId,
        status: info.status,
        fid: info.id,
      };
    }
    if (isEmpty(curUer.value)) return createMessage.warning('请选择项目经理');
    let data = {
      orgId: selectTreeId.value,
      userId: (curUer.value as any)?.id,
      realName: (curUer.value as any)?.realName,
      spStatus: type,
      salesProjectCode: props.salesCode,
      fid: orgManagerId.value,
      ...where,
    };
    console.log("1.2-暂存或提交参数-data", data);
    
    const res = await orgManagerSave(data);
    createMessage.success(res.msg);
    emits('submited');
  };

  const getDetail = async (code) => {
    let salesCode = props.salesCode || code;
    if (!salesCode) return;
    const res = await getLatestDetailCode({ salesProjectCode: salesCode, type: 2 });
    let projectManagerInfo = res.data.orgManager; // res.data;
    // 回显暂存的数据 [所选人员、左边树的选择]
    state.curUer = projectManagerInfo ? { ...projectManagerInfo, id: projectManagerInfo.userId } : {};
    if(!isNewVersion.value){
      let unitId = projectManagerInfo?.orgId;
      let treeKeys = unitId ? [unitId] : res.data?.salesDevelopmentCompany;
      leftTreeRef.value?.setSelectedKeys(treeKeys);
      selectTreeId.value = unitId || '';
      if(isFlow.value) state.userList=[state.curUer];
    };
    getDeptUserList();
  };

  watch(
    () => props.salesCode,
    async newVal => {
      if (newVal) {
        if (isFlow.value) return;
        getDetail('');
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  const dataFormSubmit = eventType => {
    if (eventType == 'save') {
      submit('0');
      return;
    }
    if (eventType == 'submit') {
      submit('1');
      return;
    }
    const formData = getData();
    emits('eventReceiver', formData, eventType);
  };

  const getData = () => {
    const data = {
      orgId: selectTreeId.value,
      userId: curUer.value.id,
      realName: curUer.value.realName,
      salesProjectCode: curUer.value.salesProjectCode,
    };
    return data;
  };

  onMounted(async () => {
    reloadTree();
    await nextTick();
    emits('setPageLoad', false);
    if (isFlow.value) {
      let formData = props.config.formData;
      state.curUer = { ...formData, id: formData?.userId };
      console.log("1.1-选中的数据", state.curUer);
      
      // getDetail(formData?.salesProjectCode);
    }
  });

  defineExpose({
    dataFormSubmit,
  });
</script>

<style lang="less" scoped>
  @import url('@/design/IlmsForm.less');
  .row{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }

  .createProjectSelect {
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    overflow-y: auto;
    .info {
      width: 200px;
      height: 80px;
      display: flex;
      cursor: pointer;
      margin: 0 10px;
      margin-bottom: 20px;

      border-radius: var(--border-radius);
      align-items: center;
      justify-content: center;
      border: 1px solid #f0f0f0;
      // &:hover {
      //   box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12),
      //     0 5px 12px 4px rgba(0, 0, 0, 0.09);
      //   border: transparent;
      // }
    }
  }

  .active {
    border: 1px solid #40a9ff !important;
    color: #40a9ff;
    font-weight: bold;
    box-shadow: 0 1px 2px -2px rgba(0, 0, 0, 0.16), 0 3px 6px 0 rgba(0, 0, 0, 0.12), 0 5px 12px 4px rgba(0, 0, 0, 0.09);
    border: transparent;
  }

  .name-eare{
    width: 200px;
    height: 80px;
    border-radius: var(--border-radius);
    margin: 0 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .project-label {
    font-size: 16px;
    margin-bottom: 12px;
  }

  .search-list {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 12px;
  }

  .IlmsForm-footer {
    border-top: 0px;
  }
</style>
